package com.example.service.impl;

import com.example.mapper.UserMapper;
import com.example.pojo.User;
import com.example.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    public UserMapper userMapper;

    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * @Author: yajie
     * @Date: 18:13 2020/7/4
     * @Parms []
     * @ReturnType: java.util.List<com.example.pojo.User>
     * @Description: 查询所有用户
     */
    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    /**
     * @Author: yajie
     * @Date: 19:56 2020/7/4
     * @Parms []
     * @ReturnType: java.util.List<com.example.pojo.User>
     * @Description: 从redis中查询用户信息
     */
    @Override
    public String getUserByRedis() {
//        //1.从缓存中根据key查询
//        //2.查询到结果返回
//        //3.如果查询结果为空，从mysql中查询，并将结果存到redis
        String userStr ="";
        userStr = (String) redisTemplate.boundValueOps("userAll").get();
        if (StringUtils.isEmpty(userStr)){
            log.info("-----------进入查询mysql的方法内-------------");
            List<User> users = userMapper.findAll();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                userStr = objectMapper.writeValueAsString(users);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            redisTemplate.boundValueOps("userAll").set(userStr);
        }
        return userStr;
    }


}
